<script setup lang="ts">
import { Markdown, TSqlInfo } from "@/models/reactiveComponent";
import { computed, inject, ref } from "vue";
import * as injectKeys from "@/services/injectKeys";
import { createSqlQueryMappingRunner } from "@/core/jsCodeRunner";
import { useElementSize, watchOnce } from "@vueuse/core";

const utilsServices = inject(injectKeys.utilsKey)!;

const props = defineProps<{ model: Markdown }>();
const model = props.model;

const ctx = model.contexts.map((ct) => {
  if (typeof ct === "string") {
    return computed(() => ct);
  }

  const sqlInfo = ct as TSqlInfo;
  const sqlQuery = utilsServices.createSqlQuery(model.id, sqlInfo.sql);
  const mapRunner = createSqlQueryMappingRunner(sqlInfo.jsMap, sqlInfo.type);

  return computed(() => {
    const data = sqlQuery.query();

    if (data.rows.length === 0) {
      return null;
    }

    return JSON.stringify(mapRunner.map(data));
  });
});

const boxRef = ref(null as unknown as HTMLDivElement);
const tableBoxHeight = ref("initial");

const { height } = useElementSize(boxRef);

watchOnce(height, (height) => {
  tableBoxHeight.value = height + "px";
});

const html = computed(() => ctx.map((v) => v.value).join(""));
</script>

<template>
  <span ref="boxRef" class="md-box" v-html="html"></span>
  <!-- <div ref="boxRef" >
        <span v-html="html"></span>
    </div> -->
</template>

<style scoped>
.md-box {
  width: 100%;
  height: v-bind(tableBoxHeight);

  & :deep(h1) {
    display: block;
    font-size: 2em;
    margin-block-start: 0.67em;
    margin-block-end: 0.67em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
    line-height: normal;
    letter-spacing: normal;
  }

  & :deep(h2) {
    display: block;
    font-size: 1.5em;
    margin-block-start: 0.83em;
    margin-block-end: 0.83em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
    line-height: normal;
    letter-spacing: normal;
  }

  & :deep(h3) {
    display: block;
    font-size: 1.17em;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
    line-height: normal;
    letter-spacing: normal;
  }

  & :deep(h4) {
    display: block;
    margin-block-start: 1.33em;
    margin-block-end: 1.33em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
    line-height: normal;
    letter-spacing: normal;
  }

  & :deep(h5) {
    display: block;
    font-size: 0.83em;
    margin-block-start: 1.67em;
    margin-block-end: 1.67em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
    line-height: normal;
    letter-spacing: normal;
  }
}
</style>
